package com.agriculture.controller;

import com.agriculture.common.CouponStatus;
import com.agriculture.common.R;
import com.agriculture.entity.Coupon;
import com.agriculture.entity.UserCoupon;
import com.agriculture.entity.ViewCoupon;
import com.agriculture.service.CouponService;
import com.agriculture.service.UserCouponService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("coupon")
public class CouponController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private UserCouponService userCouponService;

    /**
     * 商家新增优惠券
     * @param coupon
     * @return
     */
    @PostMapping("/add")
    public R<String> addCoupon(@RequestBody Coupon coupon){
        couponService.save(coupon);
        return R.success("新增优惠券成功！");
    }

    /**
     * 商家删除优惠券
     * @param coupon
     * @return
     */
    @PutMapping("/{id}")
    public R<String> delCoupon(@RequestBody Coupon coupon){
        coupon.setIsDeleted(CouponStatus.DELETED);
        couponService.updateById(coupon);
        return R.success("优惠券删除成功！");
    }

    /**
     * 用户添加优惠券
     * 即添加 user_id 字段
     * @param userCoupon
     * @return
     */
    @PostMapping("/get")
    public R<String> addCouponById(@RequestBody UserCoupon userCoupon){
        userCouponService.save(userCoupon);
        return R.success("添加优惠券成功！");
    }

    /**
     * 用户使用优惠券
     * 即设置状态 status 为 USED
     * @param userCoupon
     * @return
     */
    @PutMapping("/used")
    public R<String> useCoupon(@RequestBody UserCoupon userCoupon){
        userCoupon.setStatus(CouponStatus.USED);
        return R.success("使用成功！");
    }


    /**
     * 根据优惠券 id 查询优惠券信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Coupon> getCoupon(@PathVariable Long id){
        return R.success(couponService.getById(id));
    }
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){


        //分页构造器
        Page<Coupon> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据Level进行排序
        queryWrapper.eq(Coupon::getIsDeleted,0);

        //分页查询
        Page<Coupon> CouponPage = couponService.page(pageInfo, queryWrapper);
        return R.success(CouponPage);
    }
}



